#ifndef NetMgr_H_
#define NetMgr_H_
#include <stdint.h>
#include <functional>
#include <thread>
#include <map>
#include <unordered_map>
#include <list>
#include <mutex>
#include <chrono>
#include <condition_variable>
#include "Pipe.h"
#include "Channel.h"
#include "TaskScheduler.h"

using Task = std::function<void()>; //定义类型
class WorkerThreadN
{
public:
	WorkerThreadN();

	int32_t StartRun();
	void StopRun();
	~WorkerThreadN();

	void UpdateChannel(ChannelPtr channel);
	void RemoveChannel(ChannelPtr& channel);

	void PostTask(Task task);

	void InvokTask(Task task);
public:



private:
	void RunLoop();
	int64_t getCurrentTicket();

private:
	std::mutex _mutex;
	std::condition_variable _condition;
	bool m_bStart = false;
	int64_t m_iTimerId = 0;

	std::list<Task> _queue;

	std::thread* m_loopThread = NULL;
	bool m_bExitThread = false;
	std::thread::id _loopThreadId;
	
	Pipe m_oPipe;

	std::mutex mutex_;
	std::unordered_map<SOCKET, ChannelPtr> channels_;
};


class EventLoopN
{
public:
	EventLoopN(const EventLoopN&) = delete;
	EventLoopN& operator = (const EventLoopN&) = delete;
	EventLoopN(uint32_t num_threads = 1);  //std::thread::hardware_concurrency()
	virtual ~EventLoopN();


	void Loop();
	void Quit();

	std::shared_ptr<WorkerThreadN> GetTaskScheduler();

	virtual void UpdateChannel(ChannelPtr channel);
	virtual void RemoveChannel(ChannelPtr& channel);

	void PostTask(Task task);
#if 0
	// 添加一个定时器
	int64_t AddTimer(int64_t iDelayUs, std::function<bool()> fcb);
	// 删除一个定时器
	int32_t DelTimer(int64_t timerId);

	// 异步任务
	void PostTask(Task task);
	// 同步执行任务
	void InvokTask(Task task);

#endif

private:
	std::mutex mutex_;
	uint32_t num_threads_ = 1;
	uint32_t index_ = 1;
	std::vector<std::shared_ptr<WorkerThreadN>> task_schedulers_;



};


class NetMgr
{
protected:
	NetMgr();

public:
	static NetMgr* GetInstance();

	int32_t Init(uint32_t num_threads = 1);

	virtual ~NetMgr();

public:

	EventLoopN m_oEventLoop;

private:
	static NetMgr m_oInstance;
};


#endif

